package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.filter.OrderedFormContentFilter;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Slf4j
@Service // 是@Component的衍生注解
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1、构造日期列表, 不需要使用到mapper, 直接从形参中进行就计算获取
        List<LocalDate> dateList = getLocalDateList(begin, end);
        //2、构造日期内的营业额
        List<Double> turnoverList = new ArrayList<>();
        // 营业额 = 订单状态已完成的订单金额
        // 查询orders表, 条件: 状态-已完成, 下单时间
        //2.1开循环
        dateList.forEach(date -> {
            //select sum(amount) from orders status = 5 and order_time between '2024-05-14 00:00:00' and '2024-05-14 24:59:59999'
            //2.2查询条件
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED); // 状态 5
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 2024-05-14 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 2024-05-14 24:59:59999
            //2.4调用mapper层方法, 获取统计金额
            Double turnover = ordersMapper.sumByMap(map);
            //2.5当日金额是null的时候, 就设置成0
            turnover = turnover == null ? 0.0 : turnover;
            //2.6添加到集合中
            turnoverList.add(turnover);
        });
        //3、构造TurnoverReportVO对象, 并返回;
        return new TurnoverReportVO().builder().dateList(StringUtils.join(dateList, ","))  // 后面学习一下这个工具类
                .turnoverList(StringUtils.join(turnoverList, ",")).build();
    }

    /**
     * 获取时间列表
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
//        StringJoiner stringJoiner = new StringJoiner(",");
        //1.1循环开始存储数据
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //输出展示
        log.info("dateList:{}", dateList);
        return dateList;
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1、构造dateList数据
        List<LocalDate> dateList = getLocalDateList(begin, end);
        //2、构造newUserList数据, 新增用户列表
        //2.1 创建即可,封装newUserList数据
        List<Integer> newUserList = new ArrayList<>();
        //3.2创建
        List<Integer> totalUserList = new ArrayList<>();
        //2.2循环遍历dateList,并开始构造newUserList
        dateList.forEach(date -> {
            //select count(*) from where create_time >= beginTime and create_time <= endTime
            //2.3构造参数
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 2024-05-14 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 2024-05-14 24:59:59999
            //2.4调用mapper层
            Integer newUserCount = userMapper.countByMap(map);
            //2.5存入到集合中
            newUserList.add(newUserCount);

            //3、构造totalUserList数据, 总用户列表
            map.put("beginTime", null); // 2024-05-14 00:00:00
            //mapper
            Integer allUserCount = userMapper.countByMap(map);
            //存入到集合中
            totalUserList.add(allUserCount);
        });
        //4、封装UserReportVO对象, 并返回
        return UserReportVO.builder().dateList(StringUtils.join(dateList, ",")).newUserList(StringUtils.join(newUserList, ",")).totalUserList(StringUtils.join(totalUserList, ",")).build();
    }

    /**
     * 订单统计逻辑处理层
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //1、获取日期列表数据 dateList
        List<LocalDate> dateList = getLocalDateList(begin, end);
        //2、获取每日总订单表数 orderCountList
        //2.1创建集合封装每日总订单数
        List<Integer> orderCountList = new ArrayList<>();
        //3.3创建集合封装每日有效订单数
        List<Integer> validOrderCountrList = new ArrayList<>();
        //------------------创建变量
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        //2.2开始遍历dateList, 并获取每一天的总订单数
        for (LocalDate date : dateList) {
            //select count(*) from orders where create_time >= begin and create_time <= end
            //2.3构造条件
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            //调用mapper
            Integer newOrderCount = ordersMapper.countByMap(map);
            //添加到集合中
            orderCountList.add(newOrderCount);
            //3、获取每日有效订单数, 以逗号分隔 validOrderCountList
            //select count(*) from orders where status = 5 and create_time >= begin and create_time <= end
            map.put("status", Orders.COMPLETED);
            //3.1调用mapper1层获取数据
            Integer validOrderEveryDayCount = ordersMapper.countByMap(map);
            //3.2存入到集合中
            validOrderCountrList.add(validOrderEveryDayCount);
            //4、获取订单总数 totalOrderCount
            totalOrderCount += newOrderCount;
            //5、有效订单数 validOrderCount
            validOrderCount += validOrderEveryDayCount;
        }

        //4.获取区间订单总数 totalOrderCount --- 写法二
//        for (Integer orderCount : orderCountList) {
//            totalOrderCount += orderCount;
//        }
        //匿名内部类
        /*totalOrderCount = orderCountList.stream().reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer num1, Integer num2) {
                return num1 + num2;
            }
        }).get();*/
        //lambda
        //totalOrderCount = orderCountList.stream().reduce((num1, num2) -> num1 + num2).get();
        //方法引用
        //totalOrderCount = orderCountList.stream().reduce((num1, num2) -> Integer.sum(num1,num2)).get();
//        totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
//        totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);


        //6、订单完成率 orderCompletionRate
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            //6.1
            orderCompletionRate = (validOrderCount + 0.0) / totalOrderCount;
        }
        //7、构造OrderReportVO,并返回
        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ",")).orderCountList(StringUtils.join(orderCountList, ",")).validOrderCountList(StringUtils.join(validOrderCountrList, ",")).totalOrderCount(totalOrderCount).validOrderCount(validOrderCount).orderCompletionRate(orderCompletionRate).build();
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1、构造nameList, 商品名称列表
        //1.1 查询订单明细表order_detail +订单表orders
        //构建集合
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        //构造参数
        Map map = new HashMap();
        map.put("status", Orders.COMPLETED); // 订单状态已完成
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN)); // 开始时间
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX)); // 结束时间
        //1.2 调用mapper层获取份数与商品列表
        List<GoodsSalesDTO> sumList = ordersMapper.sumTop10(map);
        //也可使用map, 最终封装成 map : name = 值 number = 值
        //遍历封装数据
        for (GoodsSalesDTO goodsSalesDTO : sumList) {
            nameList.add(goodsSalesDTO.getName());
            //2、构造numberList, 商品销量(份数)列表
            numberList.add(goodsSalesDTO.getNumber());
        }
        //3、封装SalesTop10ReportVO对象, 并返回
        return SalesTop10ReportVO.builder().nameList(StringUtils.join(nameList, ",")).numberList(StringUtils.join(numberList, ",")).build();
    }


    /**
     * 导出运行数据报表
     *
     * @param response
     */
    @Override
    public void exportBusiessData(HttpServletResponse response) {
        //1、查询数据库,获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //1.1查询数据库
        //还需要转成LocalDateTime
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2、通过POI将数据写入到excel文件中                                                //加上后缀
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //3、通过输出流将Excel文件下载到客户端浏览器
        try {
            //3.1基于模版创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //3.2获取表格
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //3.3 填充数据-时间
            sheet.getRow(1).getCell(1).setCellValue("时间" + dateBegin + "至" + dateEnd);

            //3.4 填充概览数据
            //获取第三行
            XSSFRow row3 = sheet.getRow(3);
            //营业额
            row3.getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            row3.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第四行
            XSSFRow row4 = sheet.getRow(4);

            //有效订单
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均可单价
            row4.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                //5、获取时间开始时间, 然后按照i进行递增, 并获取每一天的数据
                LocalDate date = dateBegin.plusDays(i);
                //5.1 查询某一天的营业额,数据
                BusinessDataVO businessEveryDayData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //5.2 获取某一行
                XSSFRow row = sheet.getRow(7 + i);
                //设置日期
                row.getCell(1).setCellValue(date.toString());
                //设置营业额
                row.getCell(2).setCellValue(businessEveryDayData.getTurnover());
                //设置有效订单
                row.getCell(3).setCellValue(businessEveryDayData.getValidOrderCount());
                //设置订单完成率
                row.getCell(4).setCellValue(businessEveryDayData.getOrderCompletionRate());
                //设置平均客单价
                row.getCell(5).setCellValue(businessEveryDayData.getUnitPrice());
                //设置新增用户数
                row.getCell(6).setCellValue(businessEveryDayData.getNewUsers());
            }

            //获取输出流, 输出到浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out); // 这样就可以达到,将excel写出到客户端, 客户端就会弹出是否保存

            //4、关闭资源
            out.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
